const fs = require("fs");
const path = require("path");
const { getIgnoreList } = require("./utils");
const { ROOT_DIR, PROJECT_NAME, TODAY, TREE_IGNORE_FILE } = require("./config");

let ignoreList = [];
const fileName = `${PROJECT_NAME}_项目结构_${TODAY}.txt`;

// 获取目录树
function getDirTree(dirPath, level = 0) {
  const items = fs.readdirSync(dirPath, { withFileTypes: true });
  const treeArr = items
    .map((item) => {
      const fileName = item.name;
      const filePath = path.join(dirPath, fileName);
      const fileInfo = {
        name: fileName,
        path: filePath,
        level: level,
      };
      if (item.isDirectory()) {
        fileInfo.type = "dir";
        // 如果是目录，递归获取子目录树, 判断目录是否存在ignoreList中
        if (ignoreList.includes(filePath)) {
          fileInfo.children = [];
          return fileInfo;
        }
        fileInfo.children = getDirTree(filePath, level + 1);
      } else {
        fileInfo.type = "file";
      }
      return fileInfo;
    })
    .sort((a, b) => {
      if (a.type === b.type) {
        return a.name.localeCompare(b.name, "zh");
      } else {
        return a.type === "dir" ? -1 : 1;
      }
    });
  return treeArr;
}

// 输出目录树到文件
function outputDirTree(dirTree, outFilePath) {
  let treeStr = "";
  function genTreeStr(tree, indent = "") {
    tree.forEach((item, index) => {
      const name = item.name;
      const type = item.type;
      const suffix = type === "file" ? "" : "/";
      treeStr += `${indent}${
        index === tree.length - 1 ? "└──" : "├──"
      } ${name}${suffix}\n`;
      if (type === "dir") {
        genTreeStr(
          item.children,
          `${indent}${index === tree.length - 1 ? "   " : "│  "}`
        );
      }
    });
  }
  genTreeStr(dirTree);
  if (outFilePath) {
    fs.writeFileSync(outFilePath, treeStr);
  }
  return treeStr;
}
// (async () => {
//   ignoreList = await getIgnoreList(TREE_IGNORE_FILE);
//   // 输出目录树到指定文件
//   //   const projectName = path.basename(ROOT_DIR);
//   const outFilePath = path.join(__dirname, `../output/${fileName}`);
//   const dirTree = getDirTree(ROOT_DIR);
//   outputDirTree(dirTree, outFilePath);

//   console.log(`"项目根目录下的目录树已输出到${outFilePath}"`);
// })();

async function getDirTreeText() {
  ignoreList = await getIgnoreList(TREE_IGNORE_FILE);
  const dirTree = getDirTree(ROOT_DIR);
  return outputDirTree(dirTree);
}

module.exports = {
  getDirTreeText,
};
